<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    class="special-upload"
    :class="editType =='detail'?'pic-preview':''"
    :cancelText="editType =='detail'?'关闭':'取消'"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <div v-if="model.productType == 1 && editType == 'detail'">
        <div class="videoBox">
            <video style="width:100%;height: 100%" :src="videoUrl" controls="controls">
              您的浏览器不支持 video 标签。
            </video>
        </div>
        <div class="imgBox">
          <img :src="item" v-for="(item,index) in fileListBp">
        </div>
        <div class="pro-info">
          <h3>{{model.name}}</h3>
          <p>{{model.companyName}}</p>
          <p class="label"><span>{{model.classifyLabelsName}}</span><span>{{model.labelsName}}</span></p>
          <div class="remark" v-html="model.productDescribe"></div>
        </div>
      </div>
      <a-form :form="form" class="production" v-else>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="产品类型">
          <!-- <a-input placeholder="请输入产品类型：0:产品 1：核心技术 2：解决方案" v-decorator="['productType', {}]" /> -->
          <a-radio-group :disabled="editType=='detail'" v-decorator="['productType', {rules:[{required:true,message:'请选择'}]}]" @change="onChange">
            <a-radio :value="0">
              产品中心
            </a-radio>
            <a-radio :value="1">
              核心技术
            </a-radio>
            <a-radio :value="2">
              解决方案
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="产品名称">
          <a-input :disabled="editType=='detail'" placeholder="请输入产品名称" v-decorator="['name', {rules:[{required:true,message:'请选择'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="大类">
          <a-input :disabled="editType=='detail'" v-show placeholder="请选择大类"  v-decorator="[ 'classifyLabels', {}]" />
          <a-input :disabled="editType=='detail'" placeholder="请选择大类" @click="showCommonModalBig" v-decorator="['classifyLabelsName', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="标签">
          <a-input :disabled="editType=='detail'" placeholder="请选择标签" v-show v-decorator="['labels', {}]" />
          <a-input :disabled="editType=='detail'" placeholder="请选择标签" @click="showCommonModal" v-decorator="['labelsName', {}]" />
          
          <!-- <a-select placeholder="请选择标签" v-decorator="[ 'labelId', {}]">
            <a-select-option v-for="(item,index) in labelArr" :value="item.id">{{item.name}}</a-select-option>
          </a-select> -->
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="图片">
          <a-upload
            name="avatar"
            :disabled="editType=='detail'"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="true"
            
            :beforeUpload="uploadPicBp">
            <a-icon type="upload"/>上传图片
          </a-upload>
          <span class="upload-card-self" v-for="(item,index) in fileListBp"><img :src="item"><a-icon v-if=
          "editType !== 'detail'" style="cursor:pointer;" type="delete" @click="deleteFileObjBp(index)"/></span>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          
          label="视频">
          <a-upload
            name="avatar"
            :disabled="editType=='detail'"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="true"
            :accept="acceptVideo"
            :beforeUpload="uploadVideo">
            <a-icon type="upload"/>上传视频
          </a-upload>
          <span class="upload-card-self" v-if="videoUrl">
            <video style="width:100%;height: 100%" :src="videoUrl" controls="controls">
            您的浏览器不支持 video 标签。
            </video>
            <a-icon style="cursor:pointer;" v-if=
          "editType !== 'detail'" type="delete" @click="deleteFileObjVideo()"/></span>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="产品描述"
          class="j-field-content">
          <j-editor :disabled="editType=='detail'" v-decorator="[ 'productDescribe', {} ]" triggerChange></j-editor>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="产品地址">
          <a-input placeholder="请输入产品地址" :disabled="editType=='detail'" v-decorator="['address', {}]" />
        </a-form-item>
		
      </a-form>
      <commonModal
      modalTitle="大类选择"
      ref="commonModalBig"
      selectType="checkbox"
      @getCommonModalData="getCommonModalDataBig"
      :columns="modalColumnsBig"
      apiUrl="/tc/label/list?type=3"
      :searchArr="searchArr"></commonModal>
      <commonModal
      modalTitle="标签选择"
      ref="commonModal"
      selectType="checkbox"
      @getCommonModalData="getCommonModalData"
      :columns="modalColumns"
      apiUrl="/tc/label/list?type=1"
      :searchArr="searchArr"></commonModal>
    </a-spin>
  </j-modal>
</template>

<script>
  import { httpAction,postAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import JEditor from '@/components/jeecg/JEditor'
  import commonModal from '@/components/commonModal'
  export default {
    name: "CompanyProductModal",
    components: { JEditor,commonModal},
    watch:{
      visible(newVal,oldVal){
        if(newVal){
          this.editType = sessionStorage.getItem('editType')
        }
      }
    },
    data () {
      return {
        editType:'',
        searchArr: [
          { label: '关键字搜索', key: 'label' }
        ],
        modalColumns: [
          { title: '标签名称', dataIndex: 'label' },
        ],
        modalColumnsBig: [
          { title: '大类名称', dataIndex: 'label' },
        ],
        labelArr:[{
          id:1,
          name:'测试'
        }],
        title:"操作",
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        loading: false,
        videoUrl:'',
        acceptVideo:'video/*',
        accept:"image/*",
        fileListBp: [],
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
        },
        url: {
          add: "/tc/companyProduct/add",
          edit: "/tc/companyProduct/edit",
          updateFile:"/tc/companyProduct/upload",
        },
      }
    },
    created () {
    },
    methods: {
      deleteFileObjVideo(){
        this.videoUrl = '';
      },
      uploadVideo(fileObj){
        let httpurl = this.url.updateFile;
        let formData = new FormData();
        formData.append('file',fileObj)
        let that = this;
        // this.fileListBp = [];
        postAction(httpurl,formData).then((res)=>{
          if(res.success){
            that.$message.success('上传成功');
            // this.form.setFieldsValue({
            //     imgPath: res.message,
            // })
            this.videoUrl = res.message;
            // this.fileListBp.push({name:fileObj.name})
            console.log('ssss',this.videoUrl)
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.confirmLoading = false;
          // that.close();
        })
        return false;
      },
      deleteFileObjBp(index){
        // this.fileListBp = [];
        this.fileListBp = this.fileListBp.filter((e,eIndex)=>{
          return index !== eIndex;
        })
      },
      uploadPicBp(fileObj){
        let httpurl = this.url.updateFile;
        let formData = new FormData();
        formData.append('file',fileObj)
        let that = this;
        // this.fileListBp = [];
        postAction(httpurl,formData).then((res)=>{
          if(res.success){
            that.$message.success('上传成功');
            // this.form.setFieldsValue({
            //     imgPath: res.message,
            // })
            this.fileListBp.push(res.message)
            // this.fileListBp.push({name:fileObj.name})
            console.log('ssss',this.fileListBp)
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.confirmLoading = false;
          // that.close();
        })
        return false;
      },
      showCommonModalBig () {
          this.$refs.commonModalBig.open()
      },
      getCommonModalDataBig(val){
        if (val.length > 0) {
              console.log('数组第一个对象', val[0])
              let labelsName = [];
              let labelIds = [];
              val.forEach((e)=>{
                labelIds.push(e.id);
                labelsName.push(e.label)
              })
              this.form.setFieldsValue({
                  classifyLabels:labelIds,
                  classifyLabelsName: labelsName.join(','),
              })
          }
      },
      showCommonModal () {
          this.$refs.commonModal.open()
      },
      getCommonModalData(val){
        if (val.length > 0) {
              console.log('数组第一个对象', val[0])
              let labelsName = [];
              let labelIds = [];
              val.forEach((e)=>{
                labelIds.push(e.id);
                labelsName.push(e.label)
              })
              
              this.form.setFieldsValue({
                  labels:labelIds,
                  labelsName: labelsName.join(','),
              })
          }
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          // getBase64(info.file.originFileObj, imageUrl => {
          //   this.imageUrl = imageUrl;
          //   this.loading = false;
          // });
        }
      },
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          this.$message.error('只能上传图片文件');
        }
        const isLt2M = file.size / 1024 / 1024 < 5;
        if (!isLt2M) {
          this.$message.error('图片大小不得超过5MB');
        }
        return isJpgOrPng && isLt2M;
      },
      beforeUploadVideo(file) {
        let isJpgOrPng = true;
        if (file.type.indexOf('mp4') == -1 && file.type.indexOf('avi') == -1 && file.type.indexOf('ogg') == -1) {
          this.$message.error('只能上传视频文件');
           isJpgOrPng = false;
        }
        const isLt2M = file.size / 1024 / 1024 < 50;
        if (!isLt2M) {
          this.$message.error('视频大小不得超过50MB');
        }
        return isJpgOrPng && isLt2M;
      },
      onChange(e){
        console.log('radio checked', e.target.value);
      },
      add () {
        this.edit({});
      },
      edit (record) {
        if(record.id){
          let httpurl = '/tc/companyProduct/queryById?id='+record.id
          httpAction(httpurl,{},'get').then((res)=>{
              if(res.success){
                  this.form.resetFields();
                  this.model = Object.assign({}, res.result);
                  let labelsName = [];
                  let labelsId = [];
                  if(res.result.labels){
                    res.result.labels.forEach((e)=>{
                      labelsId.push(e.id);
                      labelsName.push(e.label)
                    })
                  }
                  
                  this.model.labels = labelsId;
                  this.model.labelsName = labelsName.join();

                  let labelsClassifyName = [];
                  let labelsClassifyId = [];
                  if(res.result.classifyLabels){
                    res.result.classifyLabels.forEach((e)=>{
                      labelsClassifyId.push(e.id);
                      labelsClassifyName.push(e.label)
                    })
                  }
                  
                  this.model.classifyLabels = labelsClassifyId;
                  this.model.classifyLabelsName = labelsClassifyName.join();
                  this.videoUrl = res.result.videoPath?res.result.videoPath:'';
                  this.fileListBp = res.result.imgPaths?res.result.imgPaths:[];
                  this.visible = true;
                  this.$nextTick(() => {
                    this.form.setFieldsValue(pick(this.model,'name','labels','labelsName','classifyLabels','classifyLabelsName','companyId','productType','companyName','productDescribe','address','createUser','updateUser','forwardCount','commentCount','fabulousCount','favoriteCount'))
                //时间格式化
                  });
              }else{
                this.$message.warning(res.message);
              }
            }).finally(() => {
              this.confirmLoading = false;
              
            })
          }else{
            this.videoUrl = '';
            this.fileListBp = [];
            this.form.resetFields();
            this.model = Object.assign({}, record);
            this.visible = true;
            this.$nextTick(() => {
              this.form.setFieldsValue(pick(this.model,'name','labels','labelsName','classifyLabels','classifyLabelsName','companyId','productType','companyName','productDescribe','address','createUser','updateUser','forwardCount','commentCount','fabulousCount','favoriteCount'))
          //时间格式化
            });
          }
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化
            formData.imgPaths = this.fileListBp;
            formData.videoPath = this.videoUrl;
            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
                that.close();
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              
            })



          }
        })
      },
      handleCancel () {
        this.close()
      },


    }
  }
</script>

<style lang="less" scoped>
  .upload-card-self{
    display:inline-block;
    width:128px;
    height:128px;
    border:dashed 1px #dedede;
    position:relative;
    box-sizing: border-box;
    background-color: #fafafa;
    margin-right: 15px;
  }
  .upload-card-self img{
    width:126px;
    height:126px;
  }
  .upload-card-self i{
    cursor: pointer;
    position: absolute;
    right: 2px;
    top: 2px;
  }
  .videoBox{
    width:500px;
    margin: 0px auto;
    height:200px;
  }
  .imgBox{
    display:flex;
    justify-content: center;
    margin-top:30px;
  }
  .imgBox img{
    width:120px;
    height:120px;
    margin-left:20px;
    border: dashed 1px #dedede;
  }
  .pro-info{
    margin-top:30px;
  }
  .pro-info h3{
    font-size:20px;
    text-align: center
  }
  .pro-info p{
    text-align:center;
    font-size:18px;
  }
  .pro-info .label{
    max-height:30px;
    overflow: hidden
  }
  .pro-info .label span{
    margin-right:20px;
  }
  .pro-info .remark{
    background-color:#f1f1f1;
    padding:15px 10px;
    border-radius:3px;
  }
</style>
<style>
  .production .ant-upload-picture-card-wrapper{
    width: 128px;
    margin-right: 15px;
  }
  .avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
  .special-upload .ant-upload-select-picture-card i{
    float: left !important;
    margin-left: 13px !important;
    font-size: 20px !important;
  }
  .special-upload .ant-upload-list-picture-card{
    display: none;
  }
  .special-upload .ant-upload-picture-card-wrapper{
    float: left;
  }
  .special-upload .ant-upload.ant-upload-select-picture-card{
    width: 128px;
    height: 128px;
  }
</style>